﻿using GalaSoft.MvvmLight;
using KINLO.Data.Reporitory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using System.Collections.ObjectModel;
using KINLO.Model;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using System.Net.Sockets;
using KINLO.UI.Main.View;
using KINLO.Model.Dto;
using System.Threading;

namespace KINLO.UI.Main.VM
{
    public class CommunicationTestVM:ViewModelBase
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MainVM));
        MachineReporitory DB = new MachineReporitory();
        CommunicationTestView View;

        public CommunicationTestVM(CommunicationTestView view)
        {
            try
            {
                this.View = view;
                var maches = DB.GetAllMachines2();
                if (maches != null && maches.Count > 0)
                {
                    Machines = new ObservableCollection<MachineDto>(maches);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        ObservableCollection<MachineDto> machines;
        public ObservableCollection<MachineDto> Machines
        {
            get { return machines; }
            set
            {
                machines = value;
                RaisePropertyChanged("Machines");
            }
        }

        //CmdCommTest
        RelayCommand cmdCommTest;
        public RelayCommand CmdCommTest
        {
            get { return cmdCommTest??(cmdCommTest=new RelayCommand(()=> DoCmdCommTest())); }
        }
        void DoCmdCommTest()
        {
            CTS = new CancellationTokenSource();
            Task.Run(() => Test());

        }
        void Test()
        {
            
            if (Machines != null && Machines.Count > 0)
            {
                foreach (var m in machines)
                {
                    m.TestResult = "";
                }
                foreach (var m in Machines)
                {
                    try
                    {
                        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        socket.ReceiveTimeout = 1000;
                        socket.SendTimeout = 1000;
                       
                        m.TestResult = "测试中 ...";
                        socket.Connect(m.IP, m.Port);
                        if (m.MachineType == 2 || m.MachineType == 4)
                        {
                            var task = Task.Run(() => ReadWeight(socket, m, CTS.Token));
                        }
                        else
                        {
                            m.TestResult = "连接成功";
                        }
                    }
                    catch (SocketException sex)
                    {
                        m.TestResult = "连接失败";
                    }
                }
            } 
        }

        RelayCommand cmdClosing;
        public RelayCommand CmdClosing
        {
            get { return cmdClosing ?? (cmdClosing = new RelayCommand(() => DoCmdClosing())); }
        }
        void DoCmdClosing()
        {
            CTS.Cancel();
        }
        CancellationTokenSource CTS;

        List<Task> Tasks = new List<Task>();
        void ReadWeight(Socket s,MachineDto m, CancellationToken token)
        {
            bool first = true;
            while (true)
            {
                if (!token.IsCancellationRequested)
                {
                    try {
                        var readByte = new byte[20];
                        var len = s.Receive(readByte);
                        if (len == 20)
                        {
                            if (first)
                            {
                                var resutl = Encoding.Default.GetString(readByte, 6, 12);
                                first = false;
                                m.WeightResult = resutl;
                                m.TestResult = "连接成功";
                            }
                            else
                            {
                                var resutl = Encoding.Default.GetString(readByte, 7, 7);
                                try
                                {
                                    var r = decimal.Parse(resutl);
                                    if (r > 0)
                                    {
                                        var resutl1 = Encoding.Default.GetString(readByte, 6, 12);
                                        m.WeightResult = resutl;
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        m.TestResult = "连接失败 电子称没打开";
                    }                    
                }
                else
                {
                    return;
                }            
            }
        }

        public override void Cleanup()
        {
            log.Info("test exit");
        }
    }
}
